import { stringify } from 'querystring';
import router from 'umi/router';
import { fakeAccountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { setUserAuthInfo } from '@/utils/userAuth';

const Model = {
    namespace: 'login',
    state: {
        status: undefined,
    },
    effects: {
        * login({ payload }, { call, put }) {
            const response = yield call(fakeAccountLogin, payload);
            if (response.code == 0) {
                response.data.userName = payload.username
                yield put({
                    type: 'changeLoginStatus',
                    payload: response.data,
                }); // Login successfully

                const urlParams = new URL(window.location.href);
                const params = getPageQuery();
                let { redirect } = params;

                if (redirect) {
                    const redirectUrlParams = new URL(redirect);

                    if (redirectUrlParams.origin === urlParams.origin) {
                        redirect = redirect.substr(urlParams.origin.length + 9);
                        if (redirect.match(/^\/.*#/)) {
                            redirect = redirect.substr(redirect.indexOf('#') + 1);
                        }

                    } else {
                        window.location.href = '/';
                        return;
                    }
                }
                router.replace(redirect || '/');
            }
        },

        // * getCaptcha({ payload }, { call }) {
        //     yield call(getlistUserJob, payload);
        // },

        logout() {
            const { redirect } = getPageQuery(); // Note: There may be security issues, please note
            setUserAuthInfo({
                accessToken: '',
                refreshToken: '',
                userName: ''
            })

            if (window.location.pathname !== '/login' && !redirect) {
                router.replace({
                    pathname: '/login',
                    search: stringify({
                        redirect: window.location.href,
                    }),
                });
            }
        },
    },
    reducers: {
        changeLoginStatus(state, { payload }) {
            setAuthority(payload.clientId);
            setUserAuthInfo({
                accessToken: payload.accessToken,
                refreshToken: payload.refreshToken,
                userName: payload.userName
            })
            return {
                ...state,
                ...payload,
            };
        },
    },
};
export default Model;